from fastapi import APIRouter, Depends
from models.Models import ArticleCategory
from db.DBUtil import DBUtil
from utils.result_back import success, fail
from datetime import datetime
from vos.Vos import ArticleCategoryVo
from fastapi_jwt_auth import AuthJWT

router = APIRouter()


@router.post("/list/{page_index}/{page_size}")
def list_category(page_index: int, page_size: int, Authorize: AuthJWT = Depends()):
    Authorize.jwt_required()
    db_util = DBUtil()
    session = db_util.get_session()
    categorys = session.query(ArticleCategory).order_by(ArticleCategory.id.desc()).limit(page_size).offset(
        (page_index - 1) * page_size).all()
    count = session.query(ArticleCategory).count()
    db_util.close()
    result = {
        'records': categorys,
        'total': count,
        'current': page_index
    }
    return success(result)


@router.get("/findById/{id}")
def find_category(id: int, Authorize: AuthJWT = Depends()):
    Authorize.jwt_required()
    db_util = DBUtil()
    session = db_util.get_session()
    category = session.query(ArticleCategory).filter(ArticleCategory.id == id).first()
    db_util.close()
    return success(category)


@router.put("/updateById")
def update_category(vo: ArticleCategoryVo, Authorize: AuthJWT = Depends()):
    Authorize.jwt_required()
    db_util = DBUtil()
    session = db_util.get_session()
    old_category = session.query(ArticleCategory).filter(ArticleCategory.id == vo.id).first()
    if old_category:
        old_category.code = vo.code
        old_category.name = vo.name
        old_category.update_time = datetime.now()
        session.commit()

    db_util.close()
    return success(old_category)


@router.post("/add")
def add_category(vo: ArticleCategoryVo, Authorize: AuthJWT = Depends()):
    Authorize.jwt_required()
    db_util = DBUtil()
    session = db_util.get_session()
    category = ArticleCategory()
    category.code = vo.code
    category.name = vo.name
    category.update_time = datetime.now()
    category.create_time = datetime.now()

    session.add(category)
    session.commit()

    db_util.close()
    return success(category)
